package pe.com.pgn.consolidadorventas.servidorestacion.util;

import org.apache.log4j.Logger;

public class ExeUtil {

	static Logger logger = Logger.getLogger(ExeUtil.class);

	public static void ejecutarPrograma(String rutaPrograma,int timeout) {
		//Ejecutamos el programa para generar sea de GLP o GNV
		Process p = null;
		Runtime aplicacion = null;
		try{
			aplicacion = Runtime.getRuntime();
			p = aplicacion.exec(rutaPrograma);
			
			long now = System.currentTimeMillis(); 
			long timeoutInMillis = 1000L * timeout; 
			long finish = now + timeoutInMillis; 
			
			if(timeout>0){
				while ( isAlive( p ) ){ 
				    Thread.sleep( timeout ); 
				    if ( System.currentTimeMillis() > finish ) {
				        p.destroy();
				        logger.info("Cerrando proceso del ejecutable , tiempo de espera excedido");
				    }
				}
			}
            
		}catch(Exception ex){
			logger.error(ex.getMessage());
		}	
	}
	
	public static boolean isAlive(Process p){
		try{
			p.exitValue();
			return false;
		} catch (IllegalThreadStateException e) {
			return true;
		}
	}
	
}

